<script setup>

import {ref, onMounted, watch, computed} from 'vue';
import axios from "axios";
import {snackbar} from './store'

// 查询
const pageSize = ref(10);
const pageNo = ref(1)
const headers = [
    {title: 'ID', key: 'id', sortable: false},
    {title: '名称', key: 'name', sortable: false},
    {title: '巡更方式', key: 'method', sortable: false},
    {title: '操作', key: 'actions', sortable: false},
];
const Methods = ref([
    { label: "顺序巡更", value: "ORDERED" },
    { label: "无序巡更", value: "UNORDERED" },
]);
const items = ref([]);
const loading = ref(true);
const totalItems = ref(0);
const isShowDialog = ref(false);
const isShowDeleteDialog = ref(false);
const editedItem = ref({});
const dialogType = ref(null)
const pointList = ref([]);
const dialogEnum = {
    update: '编辑',
    create: '新增'
}
const openPoints = ref(false);
const checkPoints = ref([]);
const addPoints = ref({
    checkpointId: null,
    sequence: ""
});
const editPoints = ref({});

const search = ref('');
const name = ref("");
watch(name, () => {
    search.value = name.value
})

function loadItems({page, itemsPerPage}) {
    loading.value = true;
    pageNo.value = page;
    pageSize.value = itemsPerPage;
    let url = `http://172.168.180.4:7000/patrol-routes?page=${page - 1}&size=${itemsPerPage}`
    if(name.value) {
        url += `&name=${name.value}`
    }
    axios({
        method: "GET",
        url: url,
        headers: {
            "Authorization": 'Bearer ' + localStorage.getItem("token")
        }
    }).then(res => {}, err => {
        items.value = err.data.content
        totalItems.value = err.data.totalElements
        loading.value = false
    })
}

function clickNew() {
    dialogType.value = dialogEnum.create
    isShowDialog.value = true
    resetEditedItem()
}

function close() {
    isShowDialog.value = false
    resetEditedItem()
    dialogType.value = null
}

function resetEditedItem() {
    editedItem.value = {
        name: ""
    }
}

function save() {
    if (dialogType.value === dialogEnum.update) {
        axios({
            method: "PUT",
            url: `http://172.168.180.4:7000/patrol-routes/${editedItem.value.id}`,
            data: editedItem.value,
            headers: {
            "Authorization": 'Bearer ' + localStorage.getItem("token")
            }
        }).then(() => {
            snackbar.info('编辑成功')
            close()
            loadItems({page: pageNo.value, itemsPerPage: pageSize.value})
        }, err => {
            snackbar.info('编辑成功')
            close()
            loadItems({page: pageNo.value, itemsPerPage: pageSize.value})
        })
    } else if (dialogType.value === dialogEnum.create) {
        axios({
            method: "POST",
            url: `http://172.168.180.4:7000/patrol-routes`,
            data: editedItem.value,
            headers: {
            "Authorization": 'Bearer ' + localStorage.getItem("token")
            }
        }).then((res) => {
            snackbar.info('创建成功')
            close()
            loadItems({page: pageNo.value, itemsPerPage: pageSize.value})
        }, err => {
            snackbar.info('创建成功')
            close()
            loadItems({page: pageNo.value, itemsPerPage: pageSize.value})
        })
    }
}

function clickEdit(row) {
    editedItem.value = row
    isShowDialog.value = true
    dialogType.value = dialogEnum.update
}

const beDeleteItem = ref({})

function clickDelete(row) {
    isShowDeleteDialog.value = true
    beDeleteItem.value = row
}

function clickDeleteConfirm() {
    axios({
        method: "DELETE",
        url: `http://172.168.180.4:7000/patrol-routes/${beDeleteItem.value.id}`,
        headers: {
            "Authorization": 'Bearer ' + localStorage.getItem("token")
        }
    }).then(() => {
        snackbar.info("删除成功")
        loadItems({page: 1, itemsPerPage: pageSize.value})
        clickCloseDelete()
    }, err => {
        snackbar.info("删除成功")
        loadItems({page: 1, itemsPerPage: pageSize.value})
        clickCloseDelete()
    })
}

function clickCloseDelete() {
    isShowDeleteDialog.value = false
    beDeleteItem.value = null
}

const selectId = ref(null);
function clickPoint(id) {
    selectId.value = id
    axios({
        method: "GET",
        url: `http://172.168.180.4:7000/patrol-route-checkpoints?routeId=${id}`,
        headers: {
            "Authorization": 'Bearer ' + localStorage.getItem('token')
        }
    }).then(res => {}, err => {
        checkPoints.value = err.data
        openPoints.value = true
    })
}

function addRoutePoint() {
    checkPoints.value.forEach(item => {
        if(item.checkpoint.id == addPoints.value.checkpointId) {
            snackbar.info("巡更点已存在！")
            return            
        }
    })
    axios({
        method: "POST",
        url: `http://172.168.180.4:7000/patrol-route-checkpoints`,
        data: {
            patrolRouteId: selectId.value,
            checkpointId: addPoints.value.checkpointId,
            sequence: addPoints.value.sequence ? addPoints.value.sequence : 999
        },
        headers: {
            "Authorization": 'Bearer ' + localStorage.getItem('token')
        }
    }).then(res => {}, err => {
        snackbar.info("新增成功")
        clickPoint(selectId.value)
    })
}

function editRoutePoint(row) {
    row.editType = true
    editPoints.value.checkpointId = row.checkpoint.id
    editPoints.value.sequence = row.sequence
    editPoints.value.patrolRouteId = selectId.value
    editPoints.value.id = row.id
}

function editRoutePointPost() {
    axios({
        method: "PUT",
        url: `http://172.168.180.4:7000/patrol-route-checkpoints/${editPoints.value.id}`,
        data: editPoints.value,
        headers: {
            "Authorization": 'Bearer ' + localStorage.getItem("token")
        }
    }).then(() => {}, err => {
        snackbar.info('编辑成功')
        clickPoint(selectId.value)
    })
}

function clickPointDelete(row) {
    axios({
        method: "DELETE",
        url: `http://172.168.180.4:7000/patrol-route-checkpoints/${row.id}`,
        headers: {
            "Authorization": 'Bearer ' + localStorage.getItem("token")
        }
    }).then(() => {}, err => {
        console.log(err)
        snackbar.info("删除成功")
        clickPoint(selectId.value)
    })
}

onMounted(() => {
    loadItems({page: 1, itemsPerPage: pageSize.value});
    axios({
        method: "GET",
        url: `http://172.168.180.4:7000/checkpoints?page=0&size=1000`,
        headers: {
            "Authorization": 'Bearer ' + localStorage.getItem("token")
        }
    }).then(res => {}, err => {
        pointList.value = err.data.content
    })
});
</script>

<template>
    <v-toolbar density="compact">
        <v-toolbar-title>巡更路线</v-toolbar-title>
        <v-text-field v-model="name" :clearable="true" hide-details placeholder="查询名称"></v-text-field>
        <v-dialog v-model="isShowDialog" max-width="500px">
            <template v-slot:activator="{ props }">
                <v-btn icon="mdi-plus" v-on:click="clickNew" v-bind="props"></v-btn>
            </template>
            <v-card>
                <v-card-title>{{ dialogType }}</v-card-title>
                <v-card-text>
                    <v-text-field v-model="editedItem.name" label="名称" required></v-text-field>
                    <v-select
                    v-model="editedItem.method"
                    label="巡更方式"
                    :items=Methods
                    item-title="label"
                    item-value="value"
                    required></v-select>
                </v-card-text>
                <v-card-actions>
                    <v-btn color="primary" variant="text" @click="close">关闭</v-btn>
                    <v-btn color="primary" variant="text" @click="save">确定</v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>
        <v-dialog v-model="isShowDeleteDialog" max-width="500px">
            <v-card>
                <v-card-title class="text-h5">删除巡更路线点将会删除与之关联的巡更记录。是否确定删除？</v-card-title>
                <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn color="blue-darken-1" variant="text" @click="clickCloseDelete">取消</v-btn>
                    <v-btn color="blue-darken-1" variant="text" @click="clickDeleteConfirm">确定</v-btn>
                    <v-spacer></v-spacer>
                </v-card-actions>
            </v-card>
        </v-dialog>
        <v-dialog v-model="openPoints" max-width="700px">
            <v-card>
                <v-card-title>巡更路线点</v-card-title>
                <v-form>
                    <v-container>
                        <v-row>
                            <v-col cols="5">
                                <v-select
                                v-model="addPoints.checkpointId"
                                :items=pointList
                                item-title="name"
                                item-value="id"
                                hide-details
                                placeholder="巡更点"
                                required></v-select>
                            </v-col>
                            <v-col cols="5">
                                <v-text-field v-model="addPoints.sequence" hide-details required placeholder="序号"></v-text-field>
                            </v-col>
                            <v-col cols="2">
                                <v-btn icon="mdi-plus" v-on:click="addRoutePoint" v-bind="props"></v-btn>
                            </v-col>
                        </v-row>
                    </v-container>
                </v-form>
                <v-card-text>
                    <div v-for="(item, index) in checkPoints" class="point" :key="item.id">
                        <p>名称：{{ item.checkpoint.name }}</p>
                        <p>序号：{{ item.sequence }}</p>
                        <v-form v-if="item.editType">
                            <v-container>
                                <v-row>
                                    <v-col cols="5">
                                        <v-select
                                        v-model="editPoints.checkpointId"
                                        :items=pointList
                                        item-title="name"
                                        item-value="id"
                                        hide-details
                                        placeholder="巡更点"
                                        required></v-select>
                                    </v-col>
                                    <v-col cols="5">
                                        <v-text-field v-model="editPoints.sequence" hide-details required placeholder="序号"></v-text-field>
                                    </v-col>
                                    <v-col cols="2">
                                        <v-btn icon="mdi-check" variant="text" v-on:click="editRoutePointPost" v-bind="props"></v-btn>
                                    </v-col>
                                </v-row>
                            </v-container>
                        </v-form>
                        <v-btn icon="mdi-pencil" variant="text" v-on:click="editRoutePoint(item)" v-bind="props"></v-btn>
                        <v-btn icon="mdi-delete" variant="text" v-on:click="clickPointDelete(item)" v-bind="props"></v-btn>
                    </div>
                </v-card-text>
            </v-card>
        </v-dialog>
    </v-toolbar>
  <!--  分页文本待更换   items-per-page-text="每页数量"-->
    <v-data-table-server :search="search" :items-per-page="pageSize" :headers="headers" :items-length="totalItems"
    :items="items"
    :loading="loading"
    class="elevation-1"
    items-per-page-text="每页数量"
    @update:options="loadItems">
        <template v-slot:item.num="{ index }">
            <span>{{ index + 1 }}</span>
        </template>
        <template v-slot:item.method="{ item }">
            <span v-if="item.raw.method == 'ORDERED'">顺序巡更</span>
            <span v-if="item.raw.method == 'UNORDERED'">无序巡更</span>
        </template>
        <template v-slot:item.actions="{ item }">
            <v-btn icon="mdi-pencil" variant="text" @click="clickEdit(item.raw)"></v-btn>
            <v-btn icon="mdi-contrast-circle" variant="text" @click="clickPoint(item.raw.id)"></v-btn>
            <v-btn icon="mdi-delete" variant="text" @click="clickDelete(item.raw)"></v-btn>
        </template>
    </v-data-table-server>
</template>

<style scoped>
.point {
    margin: 15px 10px;
    padding: 0px 10px;
    border: 1px solid #aaaaaa;
    border-radius: 20px;
}
</style>
